import {
	toast,
	dialog
} from "vant";

export const mymixins = {
	data() {
		return {
		}
	},
	methods: {
		getWeixinConfig() {
		  const _this = this;
		  let params = {}
		  _this.$request.getWeixinConfig(params).then(res=>{
			  // alert("getWeixinConfig:"+JSON.stringify(res))
		    _this.$store.commit('setAppid', res.data.value.appid)
		    _this.$store.commit('setSecret', res.data.value.secret)
		    _this.$store.commit('setMininum', res.data.value.minimum) // 最小提现金额
		    localStorage.setItem("MININUM", res.data.value.minimum)
		    //_this.getCode(res.data.value.appid)
		    if (process.env.NODE_ENV == 'production') {
		      _this.getCode(res.data.value.appid)
		    }
		  })
		},
		getCode (appid) { // 非静默授权，第一次有弹框
		  const _this = this;
		  const code = this.getUrlParam('code') // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
		  const local = window.location.href
		  if (code == null || code === '') {
		    window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+ appid +'&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
		  } else {
		    _this.$store.commit('setCode', code)
			// alert(('setCode:'+code))
		    _this.getOpenId(code) //把code传给后台获取用户信息
		  }
		},
		getUrlParam(name) {
		  var reg=new RegExp('(^|&)'+name+'=([^&]*)(&|$)')
		  var r=window.location.search.substr(1).match(reg)
		  if(r!=null) return unescape(r[2])
		  return null
		},
		getOpenId(code) {
		  const _this = this;
		  let params = {
		      appid: _this.$store.state.appid,
		      secret: _this.$store.state.secret,
		      code: code
		  }
		  // alert("params:"+JSON.stringify(params))
		  _this.$request.getOpenid(params).then(res=>{
			  // alert("getOpenid:"+JSON.stringify(res))
		      const userInfo = res.data[0];
		      const openid = userInfo["openid"];
		      const nickname = userInfo["nickname"];
		      const headimgurl = userInfo["headimgurl"];
		      const province = userInfo["province"]
		      const city = userInfo["city"]
		      _this.$store.commit('setOpenid', openid)
			  console.log("openid",openid)
		      localStorage.setItem('openid', openid)
			  // alert("openid:"+openid)
		      const item = {
		        openid,
		        nickname,
		        avatar:headimgurl,
		        province,
		        city,
		        name:nickname
		      }
			  localStorage.setItem('userInfo', JSON.stringify(item))
		      _this.$store.commit('setUserInfo',item)
			  if(localStorage.getItem('openid')) {
			  				  
			  }else{
				localStorage.setItem('openid', openid)
			  }
		      // _this.getFansItem(item)
		  })
		}
	}
}
